import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
import operator
import math


def get_sorted_points(points: list):
        """
        将多边形的顶点逆时针排序
        """
        coords = points
        center = tuple(
                map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coords), [len(coords)] * 2))
        coords = sorted(coords, key=lambda coord: (-135 - math.degrees(
                math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360, reverse=True)
        coords = np.array(coords)
        return coords


def plot_polygon(xx, alpha=0.3):
        plt.figure()
        t1 = plt.Polygon(xx, alpha=alpha)
        plt.gca().add_patch(t1)
        plt.scatter(xx[:, 0], xx[:, 1], s=30)
        plt.scatter([0], [0], s=170)

        plt.show()


def plot_polygon_ls(xx_ls: list, color_ls: list=None, alpha=0.3):
        plt.figure()

        if color_ls is None:
                color_ls = ['yellow'] * len(xx_ls)

        for i in range(len(xx_ls)):
                xx = xx_ls[i]
                color = color_ls[i]
                xx = get_sorted_points(xx)

                t1 = plt.Polygon(xx, color=color, alpha=alpha)
                plt.gca().add_patch(t1)
                plt.scatter(xx[:, 0], xx[:, 1], s=30)
                plt.scatter([0], [0], s=170)

        plt.show()

if __name__ == '__main__':
        xx = np.array([
                [-0.4, 2],
                [5, -5],
                [1, -5],
        ])

        aa = np.array([[1, 4],
               [0, 2],
               [1, 1],
               [3, 3]]
                )

        plot_polygon(xx)
        plot_polygon_ls([xx, aa])